import { Component, createRef } from "react";
import { init, type EChartsType } from "echarts";

interface IProps {
  data: { label: string; value: number }[];
}

export default class Chart04 extends Component<IProps> {
  boxRef = createRef<HTMLDivElement>();
  ins: EChartsType | null = null;

  render() {
    return (
      <div ref={this.boxRef} style={{ width: "100%", height: "100%" }}></div>
    );
  }

  componentDidMount() {
    this.initChart();
  }

  componentDidUpdate(prevProps: Readonly<IProps>): void {
    // 控制只有 data 数据发现变化，才处理
    if (this.props.data === prevProps.data) {
      return;
    }

    const { data } = this.props;
    // 重新调用 this.ins.setOption
    this.ins?.setOption({
      series: [
        {
          data: data.map((item) => ({ value: item.value, name: item.label })),
        },
      ],
    });
  }

  // 初始化
  initChart = () => {
    this.ins = init(this.boxRef.current);
    // 设置默认的配置
    this.ins.setOption({
      title: {
        text: "访问来源",
        subtext: "全站来源统计",
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          radius: "50%",
          data: [
            // { value: 1048, name: "Search Engine" },
            // { value: 735, name: "Direct" },
            // { value: 580, name: "Email" },
            // { value: 484, name: "Union Ads" },
            // { value: 300, name: "Video Ads" },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    });
  };
}
